﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class Training : System.Web.UI.Page
    {
        protected void Page_PreRender()
        {
            int counter = 0;
            foreach (GridViewRow row in GridView1.Rows)
            {
                counter += int.Parse((row.FindControl("Hours1DropDownList") as DropDownList).SelectedValue);
                counter += int.Parse((row.FindControl("Hours2DropDownList") as DropDownList).SelectedValue);
            }

            counter += int.Parse((TeamDetailsFormView.FindControl("StaminaDropDownList") as DropDownList).SelectedValue);
            counter += int.Parse((TeamDetailsFormView.FindControl("GlueDropDownList") as DropDownList).SelectedValue);
            counter += int.Parse((TeamDetailsFormView.FindControl("SetPiecesDropDownList") as DropDownList).SelectedValue);

            TotalHoursLabel.Text = counter.ToString();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                Response.Redirect("~/Default.aspx");
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.Training_PageTitle;
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            if (Request.QueryString["ConfirmMessage"] != null)
            {
                //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Green;
                //CoachMessageLabel.SkinID = "ConfirmLabel";
                this.CoachMessageLabel.Text = Request.QueryString["ConfirmMessage"].ToString();
            }
            
            if (ou.TeamId == "Null")
                Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");

            
            SubmitButton.Attributes.Add("onclick", "javascript:if(confirm('" + Resources.Resource.Training_SureSubmitTrainingInstructions + "')== false) return false;");
            this.TeamDetailsSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
            this.TrainingGetCurentPlayerInstructionsSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
            this.ShowPlayerAttributeValuesSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
            string CoachId = null;
            CoachId = (GND.ReadNivdalIntData("@UserId", "Nivdal_GetCoachByUser", ou.UserId));
            if ((CoachId == null))
                Response.Redirect("~/Default.aspx");
            if ((CoachId == "0"))
            {
                //this.CoachMessageLabel.SkinID = "ConfirmLabel";
                this.CoachMessageLabel.Text = Resources.Resource.Training_TeamDoesNotHaveACoach;
                this.SearchCoachButton.Visible = false;
                this.GetFreeCoachButton.Visible = true;
            }
            if (CoachId != "0")
            {
                this.GetFreeCoachButton.Visible = false;
                this.SubjectFormView.Visible = true;
                this.CoachDetailsLabel.Visible = true;
                if (!IsPostBack)
                {
                    this.GetCoachDetailsSqlDataSource.SelectParameters.Add("CoachId", CoachId);
                    this.GetCoachDetailsSqlDataSource.SelectParameters.Add("Language", ou.Language);
                }
                this.RedSearchCoachButton.Visible = false;
            }
            this.GetCurrentTeamGlueAndSPDataSourse.SelectParameters.Add("TeamId", ou.TeamId);
            this.NextTrainingLabel.Text = GND.ReadNivdalStringData("@TeamId", "Nivdal_GetNextTrainingDateString", ou.TeamId);
            this.NumberOfPlayers.Value = GND.ReadNivdalStringData("@TeamId", "Nivdal_GetNumberOfTeamPlayers", ou.TeamId);

            // deal with niewbie tips
            if (!IsPostBack)
            {
                if ((int)Session["NewbieTipStage"] == 1)
                {
                    Session["NewbieTipStage"] = 2;
                    Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", "2", ou.Language);
                    GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "2");
                }
            }


        }

        protected void Training1DropDownList_DataBinding(object sender, EventArgs e)
        {
            DropDownList DDL = (DropDownList)GridView1.FindControl("ConditionDropDownList");
        }

        protected void SetDefVal(Object DefVal)
        {
            DropDownList DDL = (DropDownList)GridView1.FindControl("ConditionDropDownList");
            DDL.SelectedValue = DefVal.ToString();

        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            bool GoodInput = true;
            const int MinTeamHours = 10;
            const int MaxTotalHours = 40;
            const int MaxPlayerHours = 10;
            int TotalHours = 0;
            DropDownList StaminaDropDownList = (DropDownList)TeamDetailsFormView.FindControl("StaminaDropDownList");
            DropDownList GlueDropDownList = (DropDownList)TeamDetailsFormView.FindControl("GlueDropDownList");
            DropDownList SetPiecesDropDownList = (DropDownList)TeamDetailsFormView.FindControl("SetPiecesDropDownList");
            TotalHours = TotalHours + Convert.ToInt16(StaminaDropDownList.SelectedValue);
            TotalHours = TotalHours + Convert.ToInt16(GlueDropDownList.SelectedValue);
            TotalHours = TotalHours + Convert.ToInt16(SetPiecesDropDownList.SelectedValue);

            if (TotalHours < MinTeamHours)
            {
                //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                //this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                this.CoachMessageLabel.Text = Resources.Resource.Training_TeamTrainingShouldBeAtleast + " " + " " + Resources.Resource.Global_Hours;
                GoodInput = false;
            }
            else
            {
                for (int i = 0; i < GridView1.Rows.Count; i++) //check inputs
                {
                    GridViewRow row = GridView1.Rows[i];
                    DropDownList Training1 = (DropDownList)row.FindControl("Training1DropDownList");
                    DropDownList Training2 = (DropDownList)row.FindControl("Training2DropDownList");
                    DropDownList Hours1 = (DropDownList)row.FindControl("Hours1DropDownList");
                    DropDownList Hours2 = (DropDownList)row.FindControl("Hours2DropDownList");
                    if ((Training1.SelectedItem.Value != "0") && (Training1.SelectedItem.Value == Training2.SelectedItem.Value))
                    {
                        //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                        //this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                        this.CoachMessageLabel.Text = Resources.Resource.Training_DuplicateAttributeInLine + " " + (i + 1).ToString();
                        GoodInput = false;
                        break;
                    }
                    if ((Convert.ToDecimal(Hours1.SelectedItem.Value)) + (Convert.ToDecimal(Hours2.SelectedItem.Value)) > MaxPlayerHours)
                    {
                        //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                       // this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                        this.CoachMessageLabel.Text = Resources.Resource.Training_playerCannotTrainMoreThen + " " + MaxPlayerHours + " " + Resources.Resource.Training_InLine + " " + (i + 1).ToString();
                        GoodInput = false;
                        break;
                    }

                    if ((Training1.SelectedItem.Value != "0") && (Convert.ToDecimal(Hours1.SelectedItem.Value) == 0))
                    {
                        //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                        //this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                        this.CoachMessageLabel.Text = Resources.Resource.Training_PlayerZeroHoursTrain + " " + (i + 1).ToString();
                        GoodInput = false;
                        break;
                    }

                    if ((Training2.SelectedItem.Value != "0") && (Convert.ToDecimal(Hours2.SelectedItem.Value) == 0))
                    {
                        //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                        //this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                        this.CoachMessageLabel.Text = Resources.Resource.Training_PlayerZeroHoursTrain + " " + (i + 1).ToString();
                        GoodInput = false;
                        break;
                    }

                    if ((Training1.SelectedItem.Value == "0") && (Convert.ToDecimal(Hours1.SelectedItem.Value) != 0))
                    {
                        //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                        //this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                        this.CoachMessageLabel.Text = Resources.Resource.Training_AttributeMissing + " " + (i + 1).ToString();
                        GoodInput = false;
                        break;
                    }

                    if ((Training2.SelectedItem.Value == "0") && (Convert.ToDecimal(Hours2.SelectedItem.Value) != 0))
                    {
                        //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                        //this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                        this.CoachMessageLabel.Text = Resources.Resource.Training_AttributeMissing + " " + (i + 1).ToString();
                        GoodInput = false;
                        break;
                    }

                    TotalHours = TotalHours + Convert.ToInt16(Hours1.SelectedItem.Value);
                    TotalHours = TotalHours + Convert.ToInt16(Hours2.SelectedItem.Value);

                }

                if (TotalHours > MaxTotalHours)
                {
                    //this.CoachMessageLabel.ForeColor = System.Drawing.Color.Red;
                    //this.CoachMessageLabel.SkinID = "RedConfirmLabel";
                    this.CoachMessageLabel.Text = Resources.Resource.Training_TotalHoursTrainingToHigh + " " + MaxTotalHours;
                    GoodInput = false;
                }
            }
            
            if (GoodInput)
            {
                string conn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                OnlineUser ou = (OnlineUser)Session["User"];
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

                // initializing new training instructions
                GND.ExecNivdalSQL("TeamId", "Nivdal_TrainingInitNewTrainingInstructions", ou.TeamId);
                
                
                for (int i = 0; i < GridView1.Rows.Count; i++) //good inputs, update the DataBase
                {
                    GridViewRow row = GridView1.Rows[i];
                    Label PlayerId = (Label)row.FindControl("PlayerIdLabel");
                    DropDownList Training1 = (DropDownList)row.FindControl("Training1DropDownList");
                    DropDownList Training2 = (DropDownList)row.FindControl("Training2DropDownList");
                    DropDownList Hours1 = (DropDownList)row.FindControl("Hours1DropDownList");
                    DropDownList Hours2 = (DropDownList)row.FindControl("Hours2DropDownList");
                    this.CoachMessageLabel.Text = PlayerId.Text.ToString();
                    if (Convert.ToDecimal(Hours1.SelectedItem.Value) > 0)
                    {
                        System.Data.SqlClient.SqlConnection
                        strConnection = new System.Data.SqlClient.SqlConnection(conn);
                        string StrSQL = "Nivdal_TrainingAddNewPlayerInstruction";
                        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@PlayerId", PlayerId.Text));
                        cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Attribute", Training1.SelectedItem.Value));
                        cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Hours", Convert.ToDecimal(Hours1.SelectedItem.Value)));

                        strConnection.Open();
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception SQLDBException)
                        {
                            Response.Write(SQLDBException.Message);
                        }

                        finally
                        {
                            strConnection.Close();
                        }

                    }

                    if (Convert.ToDecimal(Hours2.SelectedItem.Value) > 0)
                    {
                        System.Data.SqlClient.SqlConnection
                        strConnection = new System.Data.SqlClient.SqlConnection(conn);
                        string StrSQL = "Nivdal_TrainingAddNewPlayerInstruction";
                        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@PlayerId", PlayerId.Text));
                        cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Attribute", Training2.SelectedItem.Value));
                        cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Hours", Convert.ToDecimal(Hours2.SelectedItem.Value)));

                        strConnection.Open();
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception SQLDBException)
                        {
                            Response.Write(SQLDBException.Message);

                        }

                        finally
                        {

                            strConnection.Close();
                        }

                    }

                }
                {   
                    System.Data.SqlClient.SqlConnection
                    strConnection = new System.Data.SqlClient.SqlConnection(conn);
                    string StrSQL = "Nivdal_TrainingAssignTeamNewInstructions";
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Stamina", StaminaDropDownList.SelectedItem.Value));
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Glue", GlueDropDownList.SelectedItem.Value));
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@SetPieces", SetPiecesDropDownList.SelectedItem.Value));
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", ou.UserId));

                    strConnection.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception SQLDBException)
                    {
                        Response.Write(SQLDBException.Message);
                    }

                    finally
                    {

                        strConnection.Close();
                    }
                }

                {
                    
                    System.Data.SqlClient.SqlConnection
                    strConnection = new System.Data.SqlClient.SqlConnection(conn);
                    string StrSQL = "Nivdal_TrainingCommitInstructions";
                    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(StrSQL, strConnection);
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@UserId", ou.UserId));

                    strConnection.Open();
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception SQLDBException)
                    {
                        Response.Write(SQLDBException.Message);

                    }

                    finally
                    {
                        strConnection.Close();
                    }

                }

                Response.Redirect("~/Training.aspx?ConfirmMessage=" + Resources.Resource.Training_ChangesUpdatedSuccessfully);

            }

        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Training.aspx?ConfirmMessage=" + Resources.Resource.Training_AllChangesResetToOriginal);

        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected void GetFreeCoach(object sender, EventArgs e)
        { 
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string CoachId = GND.ReadNivdalIntData("TeamId", "Nivdal_TrainingGetBasicCoach", ou.TeamId);
            Response.Redirect("~/coach.aspx?Id=" + CoachId);                
        }


    }
}